package com.xpd.spring.aop;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

//基于继承实现
//动态代理
public class CGLIB {
    public static void main(String[] args) {
        Person fangdong=new fangdong();
        Person person=new zhongjie(fangdong);
        person.say();
    }
    public static <T> T proxy(T target){
        Enhancer enhancer=new Enhancer();
        enhancer.setSuperclass(target.getClass());
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object o,  //代理对象
                                    Method method,
                                    Object[] objects,
                                    MethodProxy methodProxy) throws Throwable {
                try {
                    System.out.println("前置增强");
                    Object invoke = method.invoke(target, objects);
                    System.out.println("返回增强");
                    return invoke;
                } catch (Exception e) {
                    System.out.println("异常增强");
                    throw new RuntimeException(e);
                } finally {
                    System.out.println("后置增强");
                }

            }
        });
        Object o = enhancer.create();
        return (T) o;
    }
}
